package com.xt.xtblesdk6;

import android.app.Activity;
import android.app.Application;
import android.app.PendingIntent;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.nfc.FormatException;
import android.nfc.NdefMessage;
import android.nfc.NdefRecord;
import android.nfc.NfcAdapter;
import android.nfc.NfcManager;
import android.nfc.Tag;
import android.nfc.tech.Ndef;
import android.os.Build;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.widget.TextView;

import androidx.annotation.RequiresApi;
import androidx.appcompat.app.AppCompatActivity;

import com.xt.pro.BLEControlJni;
import com.xt.pro.BleNFCBindInfo;
import com.xthh.XTCore;
import com.xthh._enum.HH_EnumErrorCode;
import com.xthh._enum.HH_EnumNfcErrorCode;
import com.xthh._function.HH_CharUtil;
import com.xthh._function.HH_Logging;
import com.xthh._function.HH_SystemUtil;
import com.xthh._function._ini.HH_INI;
import com.xthh._struct.HH_T_SystemParams;

import java.io.IOException;
import java.util.Arrays;

public class NFCBindActivity2 extends AppCompatActivity implements View.OnClickListener{

    private static final String TAG = "NFCBindActivity";
    Context ctx;

    TextView textView_title;
    TextView textView_content;
    public static HandlenRecvMessage handlenRecvMessage;
    private NfcAdapter mNfcAdapter;
    private PendingIntent mPendingIntent;
    HH_T_SystemParams systemParams;
    boolean nfcBindState = false;
    boolean bAutoNfcClose = false;
    boolean bIsNfcCloseInfo = false;
    public final int MSG_NFC_STATE = 2001;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_nfcbind);
        ctx = this;

        // 设置状态栏字体颜色
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
            getWindow().getDecorView().setSystemUiVisibility(View.SYSTEM_UI_FLAG_LIGHT_STATUS_BAR | View.SYSTEM_UI_FLAG_LIGHT_NAVIGATION_BAR);
            getWindow().setStatusBarColor(getColor(R.color.transparent));
            getWindow().setNavigationBarColor(getColor(R.color.transparent));
        }

        initView();

        handlenRecvMessage = new HandlenRecvMessage();

        systemParams = new HH_T_SystemParams(getApplication(), ctx, handlenRecvMessage);
    }


    // 监听各种状态
    public class HandlenRecvMessage extends Handler {
        @RequiresApi(api = Build.VERSION_CODES.JELLY_BEAN_MR2)
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);

            switch (msg.what) {
                case MSG_NFC_STATE:{
                    HH_EnumNfcErrorCode errorCode = HH_EnumNfcErrorCode.values()[msg.arg2];
                    switch (errorCode){
                        case BIND_INFO:     {
                            BleNFCBindInfo bindInfo = (BleNFCBindInfo)msg.obj;
                            if (bindInfo == null)
                                break;

                            if (bindInfo.deviceNumber != 113){
                                textView_content.setText("设备不匹配");
                                break;
                            }

                            String info = String.format("%d,%d,%s,%s,%s,%s,%s",
                                    bindInfo.deviceWidth, bindInfo.deviceHeight,
                                    bindInfo.deviceColor,
                                    bindInfo.mac,
                                    bindInfo.customerCode,
                                    bindInfo.customSN,
                                    bindInfo.customSRRC);
                            HH_Logging.i(TAG, info);

                            textView_content.setText(info);

                            HH_INI.putInt(systemParams, "DEVICE_NUMBER", bindInfo.deviceNumber);
                            HH_INI.putInt(systemParams, "DEVICE_W", bindInfo.deviceWidth);
                            HH_INI.putInt(systemParams, "DEVICE_H", bindInfo.deviceHeight);
                            HH_INI.putString(systemParams, "DEVICE_MAC", bindInfo.mac);
                            HH_INI.putString(systemParams, "DEVICE_CODE", bindInfo.customerCode);
                            HH_INI.putDeviceColor(systemParams, "DEVICE_COLOR", HH_SystemUtil.MadeColorType(bindInfo.deviceColor));
                            HH_INI.putString(systemParams, "DEVICE_COLOR_S", bindInfo.deviceColor);

                            HH_INI.putString(systemParams, "DEVICE_SN", bindInfo.customSN);
                            HH_INI.putString(systemParams, "DEVICE_SRRC", bindInfo.customSRRC);

                            nfcBindState = true;

                            Intent result = new Intent();
                            setResult(RESULT_OK, result);
                            finish();

                            /*deviceW = bindInfo.deviceWidth;
                            deviceH = bindInfo.deviceHeight;
                            deviceColorType = HH_SystemUtil.MadeColorType(bindInfo.deviceColor);
                            testMac = bindInfo.mac;

                            HH_INI.putInt(systemParams, "DEVICE_W", deviceW);
                            HH_INI.putInt(systemParams, "DEVICE_H", deviceH);
                            HH_INI.putString(systemParams, "DEVICE_MAC", bindInfo.mac);
                            HH_INI.putDeviceColor(systemParams, "DEVICE_COLOR", deviceColorType);

                            textView_w.setText(String.format("%d", deviceW));
                            textView_h.setText(String.format("%d", deviceH));
                            textView_mac.setText(testMac);
                            textView_color.setText(String.format("%d", deviceColorType.ordinal()));


                            if (bindInfo.deviceNumber == 113){
                                if (bindInfo.customSN != null && bindInfo.customSN.length() == 17){
                                    HH_T_SNInfo snInfo = XTCore.GetTagSNInfo(bindInfo.customSN);
                                    mAdapterCurrentTaskLogInfo.addTaskInfo(String.format("SN：项目代码=%s;手机型号=%s;款式类型=%s;年=%s;月=%s;日=%s;产品流水号=%s",
                                            snInfo.getProjectCode(),
                                            snInfo.getPhoneModel(),
                                            snInfo.getStyleType(),
                                            snInfo.getYear(),
                                            snInfo.getMonth(),
                                            snInfo.getDay(),
                                            snInfo.getSerialNumber()));
                                }
                            }
                            mAdapterCurrentTaskLogInfo.addTaskInfo(String.format("新绑定：%s,%d,%d,%d", testMac, deviceW, deviceH, deviceColorType.ordinal()));
*/
                            break;
                        }
                        case INCOMPATIBLE_TAG:{
                            //mAdapterCurrentTaskLogInfo.addTaskInfo("不兼容标签");
                            textView_content.setText("设备不匹配-不兼容标签");
                            break;
                        }
                        case ABNORMAL_TAG:{
                            //mAdapterCurrentTaskLogInfo.addTaskInfo("无效标签");
                            textView_content.setText("设备不匹配-无效标签");
                            break;
                        }
                        case DISABLE:{
                            //mAdapterCurrentTaskLogInfo.addTaskInfo("NFC 不存在或未打开");
                            textView_content.setText("设备不匹配-NFC 不存在或未打开");
                            break;
                        }
                        case ABNORMAL_DATA:{
                            //mAdapterCurrentTaskLogInfo.addTaskInfo("数据异常");
                            textView_content.setText("设备不匹配-数据异常");
                            break;
                        }
                    }

/*
                    mAdapterCurrentTaskLogInfo.notifyDataSetChanged();
                    if (mAdapterCurrentTaskLogInfo.getCount() > 0)
                        list_log_info.setSelection(mAdapterCurrentTaskLogInfo.getCount() - 1);
*/
                    break;
                }
            }
        }
    }


    private void initView() {
        textView_title = findViewById(R.id.textView_title);
        textView_content = findViewById(R.id.textView_content);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
    }

    @Override
    public void onClick(View v) {
        finish();
    }

    protected void onStart() {
        super.onStart();
        if (!this.hasNfc(this)) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams((Application)null, (Context)null, this.handlenRecvMessage), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.DISABLE.ordinal());
        }

        if (this.mNfcAdapter != null) {
            int flag = 0;
            this.mPendingIntent = PendingIntent.getActivity(this, 0, (new Intent(this, this.getClass())).addFlags(Intent.FLAG_ACTIVITY_SINGLE_TOP), flag);
        }

    }

    String ReadNfcInfo(Tag tag) {
        if (tag == null) {
            HH_SystemUtil.SendMessage(new HH_T_SystemParams((Application)null, (Context)null, this.handlenRecvMessage), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.ABNORMAL_TAG.ordinal());
            return null;
        } else {
            String sMac = null;
            Ndef isoDep = Ndef.get(tag);
            if (isoDep != null) {
                try {
                    if (!isoDep.isConnected()) {
                        isoDep.connect();
                    }

                    NdefMessage ndefReadMessage = null;

                    try {
                        ndefReadMessage = isoDep.getNdefMessage();
                    } catch (FormatException var20) {
                    } catch (IOException var21) {
                    }

                    if (ndefReadMessage != null) {
                        NdefRecord[] nrArray = ndefReadMessage.getRecords();
                        String sReadAll = "";

                        for(int i = 0; i < nrArray.length; ++i) {
                            NdefRecord record = nrArray[i];
                            byte[] bRecvOrder = parseTextRecord(record);
                            sReadAll = new String(bRecvOrder);
                            if (sReadAll != null && sReadAll.length() > 0) {
                                break;
                            }
                        }

                        byte[] bNfcInfo = HH_CharUtil.StringToByte2(sReadAll, "GB2312");
                        BleNFCBindInfo nfcInfo = BLEControlJni.GetBleNFCBindInfo(bNfcInfo, bNfcInfo.length);
                        if (nfcInfo != null && nfcInfo.mac.length() == 12) {
                            if (nfcInfo.customSN == null) {
                                nfcInfo.customSN = "";
                            }

                            if (nfcInfo.customSRRC == null) {
                                nfcInfo.customSRRC = "";
                            }

                            if (nfcInfo.customerCode == null) {
                                nfcInfo.customerCode = "";
                            }

                            sMac = nfcInfo.mac;
                            HH_SystemUtil.SendMessage(new HH_T_SystemParams((Application)null, (Context)null, this.handlenRecvMessage), MSG_NFC_STATE, nfcInfo, 0, HH_EnumNfcErrorCode.BIND_INFO.ordinal());
                        } else {
                            HH_SystemUtil.SendMessage(new HH_T_SystemParams((Application)null, (Context)null, this.handlenRecvMessage), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.ABNORMAL_DATA.ordinal());
                        }
                    }
                } catch (Exception var22) {
                    HH_SystemUtil.SendMessage(new HH_T_SystemParams((Application)null, (Context)null, this.handlenRecvMessage), MSG_NFC_STATE, "", 0, HH_EnumNfcErrorCode.INCOMPATIBLE_TAG.ordinal());
                } finally {
                    try {
                        isoDep.close();
                    } catch (IOException var19) {
                        var19.printStackTrace();
                    }

                }
            }

            return sMac;
        }
    }

    protected void onNewIntent(Intent intent) {
        super.onNewIntent(intent);
        Tag tag = (Tag)intent.getExtras().getParcelable("android.nfc.extra.TAG");
        final String mac = this.ReadNfcInfo(tag);
        if (this.bAutoNfcClose && mac != null && mac.length() == 12) {
            if (!bIsNfcCloseInfo) {
                HH_Logging.i("XTBaseNFCActivity", "正在处理断电任务", new Object[0]);
                (new Thread(new Runnable() {
                    public void run() {
                        try {
                            bIsNfcCloseInfo = true;
                            HH_EnumErrorCode code = XTCore.NFCClose(systemParams, mac, "");
                            bIsNfcCloseInfo = false;
                            HH_Logging.i("XTBaseNFCActivity", "断电完成", new Object[0]);
                        } catch (Exception var2) {
                            var2.printStackTrace();
                        }

                    }
                })).start();
            } else {
                HH_Logging.i("XTBaseNFCActivity", "断电未结束", new Object[0]);
            }
        }

    }

    public static byte[] parseTextRecord(NdefRecord ndefRecord) {
        if (ndefRecord.getTnf() != 1) {
            return null;
        } else if (!Arrays.equals(ndefRecord.getType(), NdefRecord.RTD_TEXT)) {
            return null;
        } else {
            try {
                byte[] payload = ndefRecord.getPayload();
                return payload;
            } catch (Exception var2) {
                throw new IllegalArgumentException();
            }
        }
    }

    protected void onResume() {
        super.onResume();
        if (this.mNfcAdapter != null && this.mPendingIntent != null) {
            this.mNfcAdapter.enableForegroundDispatch(this, this.mPendingIntent, (IntentFilter[])null, (String[][])null);
        }

    }

    protected void onPause() {
        super.onPause();
        if (this.mNfcAdapter != null) {
            this.mNfcAdapter.disableForegroundDispatch(this);
        }

    }

    public boolean hasNfc(Activity context) {
        NfcManager manager = (NfcManager)context.getSystemService(Context.NFC_SERVICE);
        this.mNfcAdapter = manager.getDefaultAdapter();
        return this.mNfcAdapter != null && this.mNfcAdapter.isEnabled();
    }

    public void GetNFCCardInfo(HH_T_SystemParams sp, boolean autoNfcClose) {
        this.systemParams = sp;
        this.bAutoNfcClose = autoNfcClose;
        if (this.mNfcAdapter != null) {
            this.mNfcAdapter.disableReaderMode(this);
        }

    }

    public void startReaderMode() {
        Bundle bundle = new Bundle();
        bundle.putInt("presence", 500);
        this.mNfcAdapter.enableReaderMode(this, new NfcAdapter.ReaderCallback() {
            public void onTagDiscovered(Tag tag) {
                ReadNfcInfo(tag);
            }
        }, 1, bundle);
    }
}
